package com.zr.controller;
import com.github.pagehelper.PageInfo;
import com.zr.controller.R.Code;
import com.zr.controller.R.Result;
import com.zr.exception.SystemException;
import com.zr.pojo.Article;
import com.zr.pojo.vo.ArticleVO;
import com.zr.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/my/article")
@CrossOrigin
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    //TODO 文章上传由于涉及文件上传需要承接表单数据(form-data格式)

    @PostMapping("/add")
    public Result addArticle(HttpServletRequest request, ArticleVO articleVO, MultipartFile cover_img) {
        String userName = (String) request.getAttribute("userName");
        //获取项目根目录，弃用
//        String realPath = request.getSession().getServletContext().getRealPath("/");

        try {
            if (cover_img != null) {
//                //获取文件的扩展名
//                String ext = FilenameUtils.getExtension(cover_img.getOriginalFilename());
//                System.out.println(ext);
                //不带后缀名的文件名
                String filename = UUID.randomUUID().toString() ;

//                String basePath = realPath + "uploads/";
                //不存储在项目目录，存储在本地目录
                String basePath = "D:\\workspace\\image\\";
                //创建一个目录对象
                File dir = new File(basePath);
                //判断当前目录是否存在
                if(!dir.exists()){
                    //目录不存在，需要创建
                    dir.mkdirs();
                }

                File newFile = new File(basePath + filename);
                cover_img.transferTo(newFile);
                Boolean flag = articleService.add(articleVO, filename, userName);
                return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, null, flag ? "添加新文章成功！" : "添加新文章失败，或存在同名文章。");
            }
        } catch (Exception e) {
            // TODO uploads是一个临时文件夹，服务器重启文件夹随即消失-弃用，存储到本地文件夹
            throw new SystemException(Code.SYSTEM_ERR, "文章上传失败。", e);
        }
        return new Result(Code.SAVE_ERR, null, "请选择文章封面后上传！");
    }

    @GetMapping("/delete/{id}")
    public Result deleteById(@PathVariable int id) {
        Boolean flag = articleService.deleteById(id);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, null, flag ? "删除文章成功！" : "删除文章失败！");
    }


    //    TODO 分页 筛选 已做
    @GetMapping("/list")
    public Result selectAll(HttpServletRequest request) {
//        System.out.println("in selectALL...");
        //获取请求查询必选参数
        int pagenum = Integer.parseInt(request.getParameter("pagenum"));
        int pagesize = Integer.parseInt(request.getParameter("pagesize"));
        //设置可选参数（筛选条件）的默认值
        int cate_id = 0;
        String state = null;

        if (request.getParameter("cate_id") != null) {
            cate_id = Integer.parseInt(request.getParameter("cate_id"));
        }
        if (request.getParameter("state") != null) {
            state = request.getParameter("state");
        }
        List<Article> articles = articleService.selectAll(pagenum, pagesize, cate_id, state);
        Boolean flag = articles != null;
        Result result = new Result(flag ? Code.GET_OK : Code.GET_ERR, articles, flag ? "查询所有文章成功！" : "暂无文章或查询失败！");
        PageInfo<Article> info = new PageInfo<>(articles);
        result.setTotal((int) info.getTotal());
        return result;
    }


    @GetMapping("/{id}")
    public Result selectById(@PathVariable int id, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("in selectById...");
        Article article = articleService.selectById(id);
        System.out.println(article);
        boolean flag = article != null;
        return new Result(flag ? Code.GET_OK : Code.GET_ERR, article, flag ? "查询文章成功！" : "暂无该文章或查询失败！");
    }

//编辑文章
    @PostMapping("/edit")
    public Result updateArticle(HttpServletRequest request, ArticleVO articleVO, MultipartFile cover_img) {
        String userName = (String) request.getAttribute("userName");
        //获取项目根目录，弃用
//        String realPath = request.getSession().getServletContext().getRealPath("/");

        try {
            if (cover_img != null) {
//                //获取文件的扩展名
//                String ext = FilenameUtils.getExtension(cover_img.getOriginalFilename());
//                System.out.println(ext);
                //不带后缀名的文件名
                String filename = UUID.randomUUID().toString() ;

//                String basePath = realPath + "uploads/";
                //不存储在项目目录，存储在本地目录
                String basePath = "D:\\workspace\\image\\";
                //创建一个目录对象
                File dir = new File(basePath);
                //判断当前目录是否存在
                if(!dir.exists()){
                    //目录不存在，需要创建
                    dir.mkdirs();
                }

                File newFile = new File(basePath + filename);
                cover_img.transferTo(newFile);

                Boolean flag = articleService.updateById(articleVO, filename);
                return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, null, flag ? "编辑文章成功！" : "编辑文章失败，或存在同名文章。");
            }
        } catch (Exception e) {
            // TODO uploads是一个临时文件夹，服务器重启文件夹随即消失-弃用，存储到本地文件夹
            throw new SystemException(Code.SYSTEM_ERR, "文章上传失败。", e);
        }
        return new Result(Code.SAVE_ERR, null, "请选择文章封面后上传！");
    }
}
